var maxZIndex =10;
var types = [
    		    {name:'String'},
    		    {name:'Integer'},
    		    {name:'Long'},
    		    {name:'Float'},
    		    {name:'Double'},
    		    {name:'Date'},
    		    {name:'Clob'},
    		    {name:'Blob'}
    		];
function typeFormatter(value){
	return value;
}
function addModel(){
	if($('#modelName').validatebox('isValid')==false){
		return;
	}
	var dname = $('#modelName').val();
	$("#modelNameHidden").val(dname);
	var html=$('#modelPanel').html();
	var obj = $(html);
	obj.attr("id",dname);
	obj.attr("title",dname);
	obj.css("display","block");
	obj.attr('class','easyui-window');
	obj.appendTo('body');
	obj.window({
		minimizable:false,
		maximizable:false,
		collapsible:false
	});
	obj.window('open');
	makeEditTable(obj);
	
	$('#addModelDialog').dialog('close');
}


function makeEditTable(table,url){
	var lastIndex;
	var currentEditFlag=true;
	table.datagrid({
		url:url,
		toolbar:[{
			text:'append',
			iconCls:'icon-add',
			handler:function(){
				table.datagrid('endEdit', lastIndex);
				var uid=new UUID().createUUID();
				table.datagrid('appendRow',{
					uid:uid,
					attrName:'FieldName',
					attrType:'String',
					attrLength:10,
					nullable:'true',
					commnent:' '
				});
				lastIndex = table.datagrid('getRows').length-1;
				table.datagrid('selectRow', lastIndex);
				table.datagrid('beginEdit', lastIndex);
				currentEditFlag=true;
			}
		},'-',{
			text:'delete',
			iconCls:'icon-remove',
			handler:function(){
				var row = table.datagrid('getSelected');
				if (row){
					var index = table.datagrid('getRowIndex', row);
					table.datagrid('deleteRow', index);
				}
				lastIndex=-1;
			}
		},'-',{
			text:'save',
			iconCls:'icon-save',
			handler:function(){
				table.datagrid('acceptChanges');
				table.datagrid('endEdit', lastIndex);
				saveModel(table);
			}
		}],
		onClickRow:function(rowIndex){
			table.datagrid('acceptChanges');
			if (lastIndex != rowIndex){
				table.datagrid('endEdit', lastIndex);
				table.datagrid('beginEdit', rowIndex);
				currentEditFlag=true;
			}else{
				if(currentEditFlag==false){
					table.datagrid('beginEdit', rowIndex);
					currentEditFlag=true;
				}else{
					table.datagrid('endEdit', rowIndex);
					currentEditFlag=false;
				}
				
			}
			lastIndex = rowIndex;
		},
		onAfterEdit:function(rowIndex,rowData,changes){
			if(changes['primary']==null){
				return;
			}else if(changes['primary']=='false'){
				return;
			}else{
				onSetPrimaryKey(table,rowIndex);
			}
		}
	});
}
function onSetPrimaryKey(table,rowIndex){
	var rows = table.datagrid('getRows');
	for(var i=0;i<rows.length;i++){
		if(i==rowIndex){
			continue;
		}
		rows[i]['primary']='false';
		table.datagrid('updateRow',{index:i,row:rows[i]});
	}
}
